package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.hfinterface.BtnClickCallBack;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerMyCollectHouseRentComponent;
import com.kmproject.haifu.mvp.contract.MyCollectHouseRentContract;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowBean;
import com.kmproject.haifu.mvp.model.entity.beans.HouseRentListShowInfoBean;
import com.kmproject.haifu.mvp.model.entity.beans.RentHouseViewHistoryBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.HouseParmarBean;
import com.kmproject.haifu.mvp.presenter.MyCollectHouseRentPresenter;
import com.kmproject.haifu.mvp.ui.activity.HousePublishMainActivity;
import com.kmproject.haifu.mvp.ui.activity.HousePublishSelectTypeActivity;
import com.kmproject.haifu.mvp.ui.activity.HouseRentShowInfoActivity;
import com.kmproject.haifu.mvp.ui.adapter.NyCollectHouseRentAdapter;
import com.kmproject.haifu.mvp.ui.adapter.RentHouseViewHistoryAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/11/2019 17:45
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MyCollectHouseRentFragment extends BaseFragment<MyCollectHouseRentPresenter> implements MyCollectHouseRentContract.View {

    @BindView(R.id.collect_house_rent_RecyclerView)
    RecyclerView collectHouseRentRecyclerView;
    @BindView(R.id.collect_house_rent_allSelect_lay)
    LinearLayout collectHouseRentAllSelectLay;
    @BindView(R.id.activity_house_rent_show_del)
    TextView activityHouseRentShowDel;
    @BindView(R.id.collect_house_rent_bottom_lay)
    LinearLayout collectHouseRentBottomLay;
    @BindView(R.id.collect_house_rent__refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.collect_house_rent_checkBox)
    CheckBox collect_house_rent_checkBox;


    Unbinder unbinder;
    NyCollectHouseRentAdapter collectHouseRentAdapter;
    private int page = 1;
//    private RentHouseViewHistoryAdapter rentHouseViewHistoryAdapter;
     private HouseParmarBean houseParmarBean = new HouseParmarBean();//查询条件对象
    public static MyCollectHouseRentFragment newInstance() {
        MyCollectHouseRentFragment fragment = new MyCollectHouseRentFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerMyCollectHouseRentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_collect_house_rent, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        houseParmarBean.setType("1");//0发布，1收藏
        UserBean userBean = DataHelper.getDeviceData(getActivity(), AppConstant.USER_INFO);//获取用户信息
        houseParmarBean.setUserId(userBean.getUserId());
        ArmsUtils.configRecyclerView(collectHouseRentRecyclerView, new LinearLayoutManager(getActivity()));
        collectHouseRentAdapter = new NyCollectHouseRentAdapter(new ArrayList<>());
        collectHouseRentRecyclerView.setAdapter(collectHouseRentAdapter);
        collectHouseRentAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        collectHouseRentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(getActivity(),HouseRentShowInfoActivity.class);
                intent.putExtra("rentId",collectHouseRentAdapter.getData().get(position).getRentId());
                UserBean userBean = DataHelper.getDeviceData(getActivity(), AppConstant.USER_INFO);//获取用户信息
                if (!userBean.getUserId().equals(collectHouseRentAdapter.getData().get(position).getUserId()))
                {
                    if (collectHouseRentAdapter.getItem(position).getIsShow()==0||collectHouseRentAdapter.getItem(position).getIsAvailable()==0)
                    {
                        showMessage("房源已失效");
                        return;
                    }
                }else {
                    intent.putExtra("type","userCenterInfo");
                }

                startActivity(intent);
            }
        });
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                houseParmarBean.setPage(page++);
                mPresenter.listHouseRentCurrentUser(houseParmarBean);
            }
        });
        collect_house_rent_checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //0表示既不是选择全部，也不是全部不选，1表示全选中  2表示全不选
                    collectHouseRentAdapter.setIsselectAll(1);
                } else {
                    collectHouseRentAdapter.setIsselectAll(2);
                }
            }
        });
//        mPresenter.getMeList(getActivity().getIntent().getIntExtra("type", 1), String.valueOf(page));

        mPresenter.listHouseRentCurrentUser(houseParmarBean);
    }

    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void getMeListSuccess(List<HouseRentListShowInfoBean> houseRentListShowInfoBeans) {
        refreshLayout.finishLoadMore();
        if (houseRentListShowInfoBeans == null || houseRentListShowInfoBeans.isEmpty()) {
            refreshLayout.setEnableLoadMore(false);
            if (page < 2) {
                //第一次请求就是空数据
                collectHouseRentAdapter.setEmptyView(AppUtil.setEmptyView(getActivity(), "您还没收藏哦！", "快去收藏吧~", null, false));
            }
            return;
        }
        if (houseRentListShowInfoBeans.size() < AppConstant.pageSize) {
            //没有下一页了
            refreshLayout.setEnableLoadMore(false);
        }else {
            refreshLayout.setEnableLoadMore(true);
        }
        collectHouseRentAdapter.setNewData(houseRentListShowInfoBeans);
    }

    @Override
    public void delSuccess() {
        showMessage("删除成功");
        //删除成功刷新界面
        houseParmarBean.setPage(1);
        mPresenter.listHouseRentCurrentUser(houseParmarBean);
//        mPresenter.getMeList(getActivity().getIntent().getIntExtra("type", 1), String.valueOf(page));
    }

    @Override
    public void viewRecordSuccess(List<RentHouseViewHistoryBean> rentHouseViewHistoryBeans) {
//        refreshLayout.finishLoadMore();
//        if (rentHouseViewHistoryBeans == null || rentHouseViewHistoryBeans.isEmpty()) {
//            refreshLayout.setEnableLoadMore(false);
//            if (page < 2) {
//                //第一次请求就是空数据
//                rentHouseViewHistoryAdapter.setEmptyView(AppUtil.setEmptyView(getActivity(), "你还没浏览记录哦！", "快去浏览吧~", null, true));
//            }
//            return;
//        }
//        if (rentHouseViewHistoryBeans.size() < AppConstant.pageSize) {
//            //没有下一页了
//            refreshLayout.setEnableLoadMore(false);
//        }
//        rentHouseViewHistoryAdapter.setNewData(rentHouseViewHistoryBeans);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        DefaultAdapter.releaseAllHolder(collectHouseRentRecyclerView);
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 控制删除
     *
     * @param showDel
     */
    public void contralList(boolean showDel) {
        if (showDel) {
            collectHouseRentBottomLay.setVisibility(View.VISIBLE);
            collectHouseRentAdapter.setShowCheck(true);
        } else {
            collect_house_rent_checkBox.setChecked(false);
            collectHouseRentBottomLay.setVisibility(View.GONE);
            collectHouseRentAdapter.setShowCheck(false);
        }
    }

    @OnClick({R.id.activity_house_rent_show_del, R.id.collect_house_rent_allSelect_lay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_house_rent_show_del:
                List<String> tems = mPresenter.getSelectIds(collectHouseRentAdapter.getData());
                if (tems.isEmpty()) {
                    showMessage("请选择要删除的内容");
                    return;
                }
                mPresenter.del(getActivity().getIntent().getIntExtra("type", 1), tems);
                break;
            case R.id.collect_house_rent_allSelect_lay:
                collect_house_rent_checkBox.setChecked(!collect_house_rent_checkBox.isChecked());
                if (collect_house_rent_checkBox.isChecked()) {
                    //0表示既不是选择全部，也不是全部不选，1表示全选中  2表示全不选
                    collectHouseRentAdapter.setIsselectAll(1);
                } else {
                    collectHouseRentAdapter.setIsselectAll(2);
                }

                break;
        }
    }
}
